package com.shujia.java.day20.demo1;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;

/**
* @Description: UDPClient 发送端
* @Author: 王火火
* @Date: 2019/8/23 8:53
 *
 *
 * 创建DatagramSocket
 * 创建IP地址和Port
 * 创建数据包（创建IP地址和Port）
 * 发送数据
 * 关闭
*/
public class UDPClient {
    public static void main(String[] args) throws Exception{
        //要发送的数据
        byte[] bytes="hello,UDP".getBytes();
        //创建DatagramSocket
        DatagramSocket datagramSocket = new DatagramSocket();
        //提供了InetAddress 127.0.0.1代表本机地址
        InetAddress ip = InetAddress.getByName("127.0.0.1");
        int port=9000;//端口号
        //创建数据包 DatagramPacket​(byte[] buf, int length,
        // InetAddress address 接收端的IP,
        // int port，接收端的port)
        DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length,ip,port);
        //发送数据send​(DatagramPacket p)
        datagramSocket.send(datagramPacket);
        System.out.println("发送端发送的数据为:"+new String(bytes,0,bytes.length));
        //关闭
        datagramSocket.close();
    }
}
